//
//  WithdrawController.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/6/10.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class WithdrawController: CBBaseViewController {

    @IBOutlet weak var lblName: UILabel!
    
    @IBOutlet weak var lblBank: UILabel!
    
    @IBOutlet weak var tfBankCard: UITextField!
    
    @IBOutlet weak var lblMoney: UILabel!
    
    @IBOutlet weak var tfMoney: UITextField!
    
    @IBOutlet weak var tfFenBank: UITextField!
    
    @IBOutlet weak var btnWithdraw: UIButton!
    
    @IBOutlet weak var lblFee: UILabel!
    
    
    weak var userModel:Variable<UserModel?>?
    var arrBank:[String] = [String]()
    
    var feeRatio:Double = 0.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我要提现"
        
        //用户数据发生变化马上刷新界面
        userModel?.asObservable()
            .subscribe(onNext: { [weak self] _ in
                self?.flushView()
            }).disposed(by: disposeBag)
        
        //读取银行卡信息
        SVProgressHUD.show()
        NetworkTool.requestData(url: ActionURL.GET_BANK_LIST, param: nil)
            .map({ [weak self] (json) -> Bool in
                self?.arrBank = (json["rows"].arrayObject as? [String]) ?? [String]()
                return true
            }).catchErrorJustReturn(false)
            .subscribe(onNext: { _ in
                SVProgressHUD.dismiss()
            }).disposed(by: disposeBag)
        //获取提现费率
        NetworkTool.requestData(url: ActionURL.GET_WITHDRWA_FEE, param: nil)
            .map { [unowned self] (json) in
                self.feeRatio = json["rows"].dictionaryValue["withdraw_service"]?.doubleValue ?? 0.0
                return true
            }.catchErrorJustReturn(false)
            .subscribe(onNext: { _ in
                SVProgressHUD.dismiss()
            }).disposed(by: disposeBag)
        
        //监听银行卡输入框
        tfBankCard.rx.controlEvent(UIControlEvents.editingChanged).asDriver()
            .drive(onNext:{ [unowned self] _ in
                let strBankcard = (self.tfBankCard.text ?? "").trim
                self.tfBankCard.text = strBankcard.bankcardFormat
            }).disposed(by: disposeBag)
        
        //监听金额输入
        tfMoney.rx.controlEvent(UIControlEvents.editingChanged).asDriver()
            .drive(onNext:{ [unowned self] _ in
                self.lblFee.text = "\((Double(self.tfMoney.text ?? "") ?? 0.0) * self.feeRatio)"
            }).disposed(by: disposeBag)
        
        //整合输入流
        let combinInput = Observable.combineLatest(tfMoney.rx.observe(String.self, "text").asObservable(), lblBank.rx.observe(String.self, "text").asObservable(), tfBankCard.rx.observe(String.self, "text").asObservable(), tfFenBank.rx.observe(String.self, "text").asObservable()) { return (money:$0 ?? "", bank:$1 ?? "", bankCard:($2 ?? "").trim, fenBank:$3 ?? "") }
            .share(replay:1)
        
        combinInput.map { input -> Bool in
            let validMoney = !input.money.isEmpty && input.money != "0"
            let validBank = !input.bank.isEmpty
            let validBankCard = !input.bankCard.isEmpty
            return validMoney && validBank && validBankCard
            }.subscribe(onNext: { [weak self] isValid in
                self?.btnWithdraw.isEnabled = isValid
                self?.btnWithdraw.alpha = isValid ? 1.0 : 0.5
            }).disposed(by: disposeBag)
        
        
        //提交提现
        btnWithdraw.rx.tap.asObservable()
            .withLatestFrom(combinInput)
            .flatMapLatest { [weak self] input -> Observable<(Bool, String)> in
                self?.view.endEditing(true)
                
                let oriMoney = Int(input.money) ?? 0
                if oriMoney % 100 != 0 {
                    return Observable.just((false,"提现金额必须为100的倍数"))
                }
                let feeMoney = Double(self?.lblFee.text ?? "") ?? 0.0
                let allAmount = Double(oriMoney) + feeMoney
                if allAmount > Double(self?.userModel?.value?.balance ?? "") ?? 0.0 {
                    return Observable.just((false,"提现金额超出用户余额"))
                }
            
                SVProgressHUD.show()
                return NetworkTool.requestData(url: ActionURL.CHARGE_OR_WITHDRAW, param: [
                    "uid":self?.userModel?.value?.uid ?? "",
                    "bank":input.bank,
                    "fen_bank":input.fenBank,
                    "card":input.bankCard,
                    "type":"4",
                    "amount":allAmount,
                    "fee":feeMoney
                    ], isShowCustomErr:false).map({ (json) -> (Bool,String) in
                        return (true, "")
                    }).catchError({ (err) -> Observable<(Bool, String)> in
                        let newErr = err as! CBNetError
                        switch newErr {
                        case let .CustomError(msg: msg, code: _):
                            return Observable.just((false,msg))
                        case .NetFailded:
                            return Observable.just((false,""))
                        case .HTTPFailed:
                            return Observable.just((false,""))
                        case .MapperError:
                            return Observable.just((false,""))
                        }
                    })
            }.observeOn(MainScheduler.instance)
            .subscribe(onNext:{ [weak self] resultCp in
                SVProgressHUD.dismiss()
                if resultCp.0 {
                    self?.clearInput()
                }
                let vwTips = (Bundle.main.loadNibNamed("ChargeWithdrawTipsView", owner: nil, options: nil)?.first as? ChargeWithdrawTipsView) ?? ChargeWithdrawTipsView()
                vwTips.show(isSuccess: resultCp.0, type: 1, tipsFailInfo: resultCp.1)
            })
            .disposed(by: disposeBag)
    }
    
    @IBAction func selectBank(_ sender: UITapGestureRecognizer) {
        self.view.endEditing(true)
        let vwPick = CBPickView(arrData: self.arrBank, strTitle: "请选择提现银行") { [weak self] (strSelectBank) in
            self?.lblBank.text = strSelectBank
        }
        vwPick.show(strSelectValue: self.lblBank.text ?? "")
    }
    
    override func setupRightBtnAction() {
        self.view.endEditing(true)
        let btnDetail = UIButton(text: "明细", color: .white, fontSize: 15.wr)
        btnDetail.cb_size = CGSize(width: 30, height: 30)
        btnDetail.rx.tap
            .subscribe(onNext:{ [weak self] _ in
                let detailVc = FundRecordController()
                self?.navigationController?.pushViewController(detailVc, animated: true)
            }).disposed(by: disposeBag)
        let rightBarButtonItem:UIBarButtonItem =
            UIBarButtonItem(customView: btnDetail)
        rightBarButtonItem.tintColor = .white
        self.navigationItem.rightBarButtonItem = rightBarButtonItem
    }
    
    //刷新视图
    func flushView() {
        lblMoney.text = userModel?.value?.balance ?? "0.0"
        lblName.text = userModel?.value?.realname ?? ""
    }
    
    func clearInput() {
        self.tfMoney.text = ""
    }

}
